<template>
  <div class="content">
    <div class="pageSearchView">
      <SearchForm v-model="searchParam" :fields="searchFields" :handleSearch="handleSearch" />
    </div>

    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">
          列表信息
        </div>
        <div class="pageTableButView">
          <el-button :icon="Plus" @click="handleAdd">新建</el-button>
          <!-- 添加列按钮 -->
          <el-button :icon="Plus" @click="showAddColumnDialog = true" type="primary">添加列</el-button>
        </div>
      </div>

      <!-- 表格 -->
      <el-table class="pageTableClass" :data="paginatedData" height="calc(100vh - 350px)" :loading="isLoading">
        <el-table-column label="序号" align="center" width="70">
          <template #default="scope">
            {{ (paginationParams.current - 1) * paginationParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="equipmentCode" label="设备编码" align="center" min-width="200" />
        <el-table-column prop="equipmentName" label="设备名称" align="center" min-width="200" />
        <el-table-column label="设备来源" align="center" min-width="100">
          <template #default="scope">
            {{ getTypeName(scope.row.equipmentType) }}
          </template>
        </el-table-column>
        <el-table-column prop="equipmentSource" label="设备分类" align="center" width="200" />
        <el-table-column prop="leaveCode" label="出厂编号" align="center" min-width="200" />

        <!-- 动态列渲染 -->
        <el-table-column v-for="col in dynamicColumns" :key="col.key" :prop="col.key" :label="col.label"
          align="center" />

        <el-table-column label="操作" align="center" fixed="right" min-width="180">
          <template #default="scope">
            <el-button @click="handleEdit(scope.row)" size="small" plain text :icon="Edit">编辑</el-button>
            <el-button @click="handleDel(scope.row)" type="danger" size="small" plain text :icon="Delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagePagination">
        <el-pagination background v-model:current-page="paginationParams.current"
          v-model:page-size="paginationParams.pageSize" layout="total, sizes, prev, pager, next" :total="pageTotal"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- 动态添加列的对话框 -->
    <el-dialog v-model="showAddColumnDialog" title="添加新列">
      <el-form>
        <el-form-item label="列名称">
          <el-input v-model="newColumn.label" placeholder="请输入列名称" />
        </el-form-item>
        <el-form-item label="列Key">
          <el-input v-model="newColumn.key" placeholder="请输入列Key" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddColumnDialog = false">取消</el-button>
        <el-button type="primary" @click="addColumn">确定</el-button>
      </template>
    </el-dialog>

    <!-- 弹窗表单 -->
    <el-dialog v-model="showCrud" :title="crudTitle">
      <el-form :model="formData" label-width="130px" ref="ruleFormRef" :rules="rules">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="设备编码" required prop="equipmentCode">
              <el-input v-model="formData.equipmentCode" placeholder="请输入设备编码" style="width: 300px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" required prop="equipmentName">
              <el-input v-model="formData.equipmentName" placeholder="请输入设备名称" style="width: 300px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备来源" required prop="equipmentType">
              <el-select v-model="formData.equipmentType" clearable style="width: 300px">
                <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备分类" required prop="equipmentSource">
              <el-input v-model="formData.equipmentSource" placeholder="请输入设备分类" style="width: 300px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出厂编号" required prop="leaveCode">
              <el-input v-model="formData.leaveCode" placeholder="请输入出厂编号" style="width: 300px" />
            </el-form-item>
          </el-col>
          <!-- 动态字段在弹窗中渲染 -->
          <el-col :span="12" v-for="col in dynamicColumns" :key="col.key">
            <el-form-item :label="col.label" :prop="col.key">
              <el-input v-model="formData[col.key]" :placeholder="`请输入${col.label}`" style="width: 300px" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="showCrud = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import SearchForm from '@/components/SearchForm.vue';
import { useEquipmentData } from '@/hooks/baseData/equipment';
import { Delete, Edit, Plus } from '@element-plus/icons-vue';
import { ElMessageBox } from 'element-plus';
import { computed, ref } from 'vue';

const {
  searchParam,
  paginationParams,
  pageTotal,
  paginatedData,
  searchFields,
  handleSearch,
  handleSizeChange,
  handleCurrentChange,
  addEquipment,
  deleteEquipment,
  isLoading,
  ruleFormRef,
  rules,
  formData
} = useEquipmentData();

// 动态列和新列的数据
const dynamicColumns = ref([]);
const showAddColumnDialog = ref(false);
const newColumn = ref({
  label: '',
  key: ''
});

// 动态添加列
const addColumn = () => {
  if (newColumn.value.label && newColumn.value.key) {
    dynamicColumns.value.push({ ...newColumn.value });
    newColumn.value = { label: '', key: '' };
    showAddColumnDialog.value = false;
  }
};

const getTypeName = (type: string) => {
  const name = typeList.value.find((item: any) => item.value === type);
  return name ? name.label : '';
};
const typeList = ref([
  { label: "自制", value: "0" },
  { label: "内购", value: "1" },
  { label: "外购", value: "2" },
  { label: "租赁", value: "3" },
  { label: "客供", value: "4" },
]);
const isEdit = ref(false);
const showCrud = ref(false);
const crudTitle = computed(() => {
  return isEdit.value ? '编辑' : '新建';
});

// 新建记录
const handleAdd = () => {
  isEdit.value = false;
  formData.value = {};
  showCrud.value = true;
};

// 编辑记录
const handleEdit = (row: any) => {
  isEdit.value = true;
  formData.value = { ...row };
  showCrud.value = true;
};

// 删除记录
const handleDel = (row: any) => {
  ElMessageBox.confirm(`确认要删除设备 "${row.equipmentName}" 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      deleteEquipment(row.id);
    })
    .catch(() => { });
};

// 保存记录
const handleSave = () => {
  if (isEdit.value) {
    // 编辑保存
    ruleFormRef.value.validate((valid: boolean) => {
      if (valid) {
        // 执行保存操作...
        addEquipment(formData.value, (() => {
          showCrud.value = false;
        }));
        showCrud.value = false;
      }
    });
  } else {
    // 新建保存
    ruleFormRef.value.validate((valid: boolean) => {
      if (valid) {
        addEquipment(formData.value, (() => {
          showCrud.value = false;
        }));
        showCrud.value = false;
      }
    });
  }
};
</script>
